import ConfigParser
import os
from helpers import *
from TileCache import TileCache

class Level(object):
    def __init__(self, filename="test.map"):
        self.tileset = ''
        self.map = []
        self.items = {}
        self.key = {}
        self.width = 0
        self.height = 0
        self.load_file(filename)
        self.map_cache = TileCache(MAP_TILE_WIDTH, MAP_TILE_HEIGHT)

        
    def load_file(self, filename="test.map"):
        parser = ConfigParser.ConfigParser()
        parser.read("maps/" + filename)
        self.tileset = parser.get("level", "tileset")
        self.map = parser.get("level", "map").split(",")
        for y, line in enumerate(self.map):
            line = line.strip()
            line = line.replace('\'', '')
            line = line.replace(']', '')
            line = line.replace('[', '')
            self.map[y] = line
        for section in parser.sections():
            if len(section) == 1:
                desc = dict(parser.items(section))
                self.key[section] = desc
        self.width = len(self.map[0])
        self.height = len(self.map)
        for y, line in enumerate(self.map):
            for x, c in enumerate(line):
                if not self.is_wall(x, y) and 'sprite' in self.key[c]:
                    self.items[(x, y)] = self.key[c]

    def get_tile(self, x, y):
        try:
            char = self.map[y][x]
        except IndexError:
            return {}
        try:
            return self.key[char]
        except KeyError:
            return {}
        
    def swap_tile(self, x, y, name='air'):
        if x >= 0 and x <= self.width-1 and y >= 0 and y <= self.height-1:
            for c in self.key:
                if self.key[c]['name'] == name:
                    maplist = list(self.map[y])
                    maplist[x] = c
                    self.map[y] = ''.join(maplist)
                    return
        
    def saveLevel (self, filename):
        config = ConfigParser.RawConfigParser()
        config.add_section('level')
        config.set('level', 'tileset', self.tileset)
        config.set('level', 'map', self.map)
        for sect in self.key:
            config.add_section(sect)
            for (key, value) in self.key[sect].items():
                config.set(sect, key, value)

        mapfile = open('maps/' + filename, 'w')
        config.write(mapfile)
        
    def get_name(self, x, y):
        if x >= 0 and x <= self.width-1 and y >= 0 and y <= self.height-1:
            return self.key[self.map[y][x]]['name']
        
    def get_bool(self, x, y, name):
        value = self.get_tile(x, y).get(name)
        return value in (True, 1, 'true', 'yes', 'True', 'Yes', '1', 'on', 'On')
        
    def is_wall(self, x, y):
        return self.get_bool(x, y, 'air')

    def render(self):
        wall = self.is_wall
        tiles = self.map_cache[self.tileset]
        image = pygame.Surface((self.width*MAP_TILE_WIDTH, self.height*MAP_TILE_HEIGHT))
        background = pygame.Surface((2*MAP_TILE_WIDTH, 2*MAP_TILE_HEIGHT))
        overlays = {}
        for map_y, line in enumerate(self.map):
            for map_x, c in enumerate(line):
                if wall(map_x, map_y):
                    tile = 2, 0
                else:
                    try:
                        tile = self.key[c]['tile'].split(',')
                        tile = int(tile[0]), int(tile[1])
                    except (ValueError, KeyError):
                        # Default to air tile
                        tile = 0, 0
                tile_image = tiles[tile[0]][tile[1]]
                image.blit(tile_image, (map_x*MAP_TILE_WIDTH, map_y*MAP_TILE_HEIGHT))
        for i in range(2):
            for j in range(2):
                tiles_bg = tiles[i + 5][j + 6]
                background.blit(tiles_bg, (i*MAP_TILE_WIDTH, j*MAP_TILE_HEIGHT))
        image.set_colorkey((255,0,255))
        return image, overlays, background